package com.study.jdbc.utils;

import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.sql.DataSource;

/**
* @Name: MyDataSourceUtil
* @Description: 自定义数据源工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-19 上午10:59:55 
* @Version: V1.0
 */
public class MyDataSourceUtil implements DataSource {
	
	private static List<Connection> pool = new ArrayList<Connection>() ;
	
	private static final int POOLSIZE = 10 ;
	
	static {
		for (int i = 0; i < POOLSIZE; i++) {
			Connection con = JDBCUtil.getConnection() ;
			pool.add(con) ;
		}
	}
	
	@Override
	public synchronized Connection getConnection() throws SQLException {
		if(pool.size() > 0) {
			final Connection con = pool.remove(0);
			Connection proxy = (Connection) Proxy.newProxyInstance(con.getClass().getClassLoader(), 
					new Class[] {Connection.class}, 
					new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					if("close".equals(method.getName())) {
						System.out.println("将数据库连接放回到连接池中！");
						return pool.add(con) ;
					} else {
						return method.invoke(con, args) ;
					}
				}
			}) ;
			return proxy ;
		} else {
			throw new RuntimeException("数据库连接获取失败！") ;
		}
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return 0;
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		return null;
	}
	

}


















